package com.achao.achaomq.controller;

import com.achao.achaomq.constants.RocketMqConstant;
import com.achao.achaomq.entity.R;
import lombok.AllArgsConstructor;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author achao
 * @date 2018/12/16
 */
@RestController
//构造器注入
@AllArgsConstructor
@RequestMapping("/achao/mq-test")
public class RocketMqController {

    @Qualifier("rocketMQTemplate")
    private final RocketMQTemplate rocketMQTemplate;


    /**
     * 发送消息到mq
     * @param msg 发送消息内容
     */
    @GetMapping("/send")
    public R send(String msg){
        //String msg = "大毛和二毛";
        sendMq(msg,rocketMQTemplate, RocketMqConstant.ACHAO_TOPIC,"消息备注信息");
        return R.successResult(msg);
    }

    /**
     * 发送数据
     *
     * @param rvo
     * @param topic
     * @return
     */
    private void sendMq(Object rvo, RocketMQTemplate rocketMqTemplate, String topic, String msg) {
        SendStatus sendStatus = rocketMqTemplate.syncSend(topic, new GenericMessage<>(rvo), RocketMqConstant.TIMEOUT).getSendStatus();
        if (!Objects.equals(sendStatus, SendStatus.SEND_OK)) {
            throw new RuntimeException(msg);
        }
    }
}


